let aceEditors = {}
import pretty from 'pretty'
import  isFunction from 'lodash/isFunction'

export function renderAceEditor(id = '', content = '', options = {}) {
  ace.config.set("workerPath", "/public")

  function getContent() {
    let _html = ''
    if (isFunction(content)) {
      _html = content()
    } else {
      _html = pretty(content)
    }
    return _html
  }

  let _content = getContent()

  if (!aceEditors[id]) {
    document.getElementById(id).innerHTML = _content
    aceEditors[id] = ace.edit(id, {
      mode: "ace/mode/html",
      selectionStyle: "text",
      ...options
    });
  } else {
    aceEditors[id].session.setValue(_content)
  }
  if (options.onEnd) {
    options.onEnd(_content)
  }

  return aceEditors[id]
}
